/*
 * Copyright (C) RT, 2017 by kiterunner_t
 * TO THE HAPPY FEW
 */

package com.zgys.mes.util.gson;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import com.zgys.mes.util.IValuedEnum;


public class ValuedIntEnumAdapter<E extends IValuedEnum>
        implements JsonSerializer<IValuedEnum>, JsonDeserializer<IValuedEnum> {

    private Class<E> valuedCls;


    public ValuedIntEnumAdapter(Class<E> cls) {
        valuedCls = cls;
    }


    @Override
    public JsonElement serialize(IValuedEnum state, Type arg1,
                                 JsonSerializationContext arg2) {
        return new JsonPrimitive(state.getId());
    }


    @Override
    public IValuedEnum deserialize(JsonElement json, Type typeOfT,
                                   JsonDeserializationContext context) throws JsonParseException {
        int n = json.getAsInt();
        E[] objs = valuedCls.getEnumConstants();
        for (E em : objs){
            if (em.getId() == n){
                return em;
            }
        }

        return null;
    }
}

